package com.atguigu.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.srb.common.exception.BusinessException;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.oss.service.FileService;
import com.atguigu.srb.oss.uitl.OssProperty;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author lsyandwh
 * @create 2022-12-09 11:28
 */
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file, String module) {

        OSS oss = new OSSClientBuilder().build(OssProperty.ENDPOINT,OssProperty.KEY_ID,OssProperty.KEY_SECRET);

        //创建文件名称
        String name = file.getOriginalFilename();
        String fileName = createFileName(name, module);
        try {
            //将文件转换成输入流
            InputStream inputStream = file.getInputStream();
            //上传文件
            oss.putObject(OssProperty.BUCKET_NAME,fileName,inputStream);
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR);
        }

        //组装文件访问路径
        String url = "https://" + OssProperty.BUCKET_NAME + "." + OssProperty.ENDPOINT  + "/" + fileName;
        return url ;
    }

    @Override
    public void removeFile(String url) {

        //组装文件前缀
        String prefix = "https://" + OssProperty.BUCKET_NAME + "." + OssProperty.ENDPOINT  + "/";

        //截取掉文件前缀
        String fileName = url.substring(prefix.length());

        OSS oss = new OSSClientBuilder().build(OssProperty.ENDPOINT,OssProperty.KEY_ID,OssProperty.KEY_SECRET);
        oss.deleteObject(OssProperty.BUCKET_NAME,fileName);
        oss.shutdown();
    }

    /**
     * 生成文件名称
     * @param file 文件名称
     * @param module 模块名称
     * @return
     */
    private String createFileName(String file,String module){
        //获取文件类型
        String fileType = file.substring(file.lastIndexOf("."));
        String s = StringUtils.getFilenameExtension(file);
        //创建文件日期名
        String dataFile = new DateTime().toString("yyyy/MM/dd");
        //创建文件名称
        String str = UUID.randomUUID().toString();
        //组装文件名称
        String fileName = module  + "/" + dataFile + "/" + str + fileType;
        return fileName;
    }
}
